package com.quanshu.exchange.ui.gui.profile;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baselibrary.util.glide.GlideUtils;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.ShopInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.MyOrderEntity;
import com.quanshu.exchange.support.entity.OrderDetailsEntity;
import com.quanshu.exchange.support.entity.TcDataBean;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.base.recycler.BaseViewHolder;
import com.quanshu.exchange.ui.base.recycler.DataDisplayer;
import com.quanshu.exchange.ui.base.recycler.LayoutWrapper;
import com.quanshu.exchange.ui.base.recycler.SingleAdapter;
import com.quanshu.exchange.ui.gui.web_page.FarmingPayActivity;
import com.quanshu.exchange.ui.gui.web_page.OrderPaymentActivity;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 订单详情
 * Created by xiniu003 on 2018/1/16.
 */

public class OrderDetailsActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.order_details_status)
    TextView orderDetailsStatus;
    @BindView(R.id.order_person_phone)
    TextView orderPersonPhone;
    @BindView(R.id.order_person_name)
    TextView orderPersonName;
    @BindView(R.id.order_person_address)
    TextView orderPersonAddress;
    @BindView(R.id.order_details_image)
    ImageView orderDetailsImage;
    @BindView(R.id.order_details_price_pianyi)
    TextView orderDetailsPricePianyi;
    @BindView(R.id.order_details_price_gui)
    TextView orderDetailsPriceGui;
    @BindView(R.id.order_details_number)
    TextView orderDetailsNumber;
    @BindView(R.id.order_details_price_llt)
    LinearLayout orderDetailsPriceLlt;
    @BindView(R.id.order_details_shop_name)
    TextView orderDetailsShopName;
    @BindView(R.id.order_details_serial_number)
    TextView orderDetailsSerialNumber;
    @BindView(R.id.order_details_order_number)
    TextView orderDetailsOrderNumber;
    @BindView(R.id.order_details_order_down_time)
    TextView orderDetailsOrderDownTime;
    @BindView(R.id.order_details_order_create_time)
    TextView orderDetailsOrderCreateTime;
    @BindView(R.id.order_details_user_massage)
    TextView orderDetailsUserMassage;
    @BindView(R.id.order_details_wuliu_xinxi)
    LinearLayout orderDetailsWuliuXinxi;
    @BindView(R.id.order_details_wuliu_gongsi)
    TextView orderDetailsWuliuGongsi;
    @BindView(R.id.order_details_kuaidi_number)
    TextView orderDetailsKuaidiNumber;
    @BindView(R.id.order_details_query_url)
    TextView orderDetailsQueryUrl;
    @BindView(R.id.order_details_shop_price)
    TextView orderDetailsShopPrice;
    @BindView(R.id.order_details_order_yunfei)
    TextView orderDetailsOrderYunfei;
    @BindView(R.id.order_details_order_zongjia)
    TextView orderDetailsOrderZongjia;
    @BindView(R.id.edit_order_details_one)
    TextView editOrderDetailsOne;
    @BindView(R.id.edit_order_details_two)
    TextView editOrderDetailsTwo;
    @BindView(R.id.order_details_type_edit)
    RelativeLayout orderDetailsTypeEdit;
    @BindView(R.id.value_added_services)
    TextView valueAddedServices;
    @BindView(R.id.post_house_addr)
    TextView postHouseAddr;
    @BindView(R.id.post_house_addr_llt)
    LinearLayout postHouseAddrLlt;

    //农产品
    @BindView(R.id.recy_nongchanpin_llt)
    LinearLayout recyNongchanpinLlt;
    @BindView(R.id.recy_nongchanpin)
    RecyclerView recyNongchanpin;
    @BindView(R.id.pay_flag)
    ImageView payFlag;
    @BindView(R.id.pay_flag_1)
    ImageView payFlag1;
    @BindView(R.id.pay_flag_2)
    ImageView payFlag2;
    @BindView(R.id.recy_card_info)
    RecyclerView recyCardInfo;
    @BindView(R.id.layout_card_info)
    LinearLayout layoutCardInfo;

    private SingleAdapter<TcDataBean> adapter;
    private OrderDetailsEntity orderDetailsEntity;
    private MyOrderEntity myOrderEntity;
    private int boat;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_details);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        String orderId = intent.getStringExtra("orderId");
        myOrderEntity = (MyOrderEntity) intent.getSerializableExtra("myOrderEntity");
        getOrderDetail(orderId);
        initListener();
    }

    private void initListener() {
        RxViewHelper.getInstance().clicks(back, aVoid -> finish());
    }

    public static void MoveToPosition(LinearLayoutManager manager, int n) {
        manager.scrollToPositionWithOffset(n, 0);
        manager.setStackFromEnd(true);
    }

    private void initData(String order_id) {
        if (orderDetailsEntity != null) {
            if (orderDetailsEntity.getCard_number() != null && orderDetailsEntity.getCard_number().size() > 0) {
                layoutCardInfo.setVisibility(View.VISIBLE);
                recyCardInfo.setLayoutManager(new LinearLayoutManager(this));
                SingleAdapter<String> cardAdapter = new SingleAdapter<>(new DataDisplayer<String>(this, R.layout.item_card_info) {
                    @Override
                    public void bindData(BaseViewHolder holder, LayoutWrapper<String> wrapper, String item, int position) {
                        holder.setText(R.id.tv_card_info, "卡号" + (position + 1) + ":  " + item);
                    }
                });
                recyCardInfo.setAdapter(cardAdapter);
                cardAdapter.setData(orderDetailsEntity.getCard_number());
            }
        } else {
            layoutCardInfo.setVisibility(View.GONE);
        }

        /**
         *  农产品的处理
         */
        if (orderDetailsEntity.getIs_inn().equals("1") &&
                !orderDetailsEntity.getOrderStatuText().equals("待付款") &&
                orderDetailsEntity.getTcData() != null &&
                orderDetailsEntity.getTcData().size() > 0) {//判断是否是农产品订单 1是0不是

            postHouseAddrLlt.setVisibility(View.VISIBLE);
            postHouseAddr.setText("驿站地址：" + orderDetailsEntity.getInn_remark());

            recyNongchanpinLlt.setVisibility(View.VISIBLE);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
            recyNongchanpin.setLayoutManager(linearLayoutManager);
            linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            MoveToPosition(linearLayoutManager, boat);

            adapter = new SingleAdapter<>(new DataDisplayer<TcDataBean>(this, R.layout.item_nongchanpin) {
                @Override
                public void bindData(BaseViewHolder holder,
                                     LayoutWrapper<TcDataBean> wrapper,
                                     TcDataBean item,
                                     int position) {
                    item = orderDetailsEntity.getTcData().get(position);

                    Log.e("0000", item.toString());

                    LinearLayout selectTaocan = holder.getView(R.id.select_taocan);//选择套餐
                    LinearLayout lookDetails = holder.getView(R.id.look_details);//查看详情
                    RelativeLayout noOpen = holder.getView(R.id.no_open);//未开启

                    if (item.getTc_detail_code() == 0) {//未开启
                        noOpen.setVisibility(View.VISIBLE);
                        selectTaocan.setVisibility(View.GONE);
                        lookDetails.setVisibility(View.GONE);
                        holder.setText(R.id.no_week, "第" + item.getWeek() + "周");

                    } else if (item.getTc_detail_code() == 1) {//选择套餐
                        noOpen.setVisibility(View.GONE);
                        selectTaocan.setVisibility(View.VISIBLE);
                        lookDetails.setVisibility(View.GONE);
                        holder.setText(R.id.select_week, "第" + item.getWeek() + "周");
                        RxViewHelper.getInstance().clicks(selectTaocan, aVoid -> {
                            DialogFarmProducts dialogFarmProducts = new
                                    DialogFarmProducts(OrderDetailsActivity.this);
                            dialogFarmProducts.show();
                            dialogFarmProducts.setData(orderDetailsEntity.getPackageData());
                            TextView textView = holder.getView(R.id.taocan_text);
                            if (textView.getText().toString().equals("选择套餐")) {
                                dialogFarmProducts.getItemClickSubject().subscribe(packageDataBean -> {
                                    dialogFarmProducts.dismiss();
                                    String taocan_id = packageDataBean.getId();
                                    doActionAdd(position, taocan_id, holder, order_id);
                                });
                            }
                        });

                    } else if (item.getTc_detail_code() == 2) {//查看详情

                        noOpen.setVisibility(View.GONE);
                        selectTaocan.setVisibility(View.GONE);
                        lookDetails.setVisibility(View.VISIBLE);

                        holder.setText(R.id.look_week, "第" + item.getWeek() + "周");

                        RxViewHelper.getInstance().clicks(lookDetails, aVoid -> {
                            Dialog_details dialog_details = new Dialog_details(OrderDetailsActivity.this);
                            dialog_details.setData(orderDetailsEntity.getTcData().get(position));
                            dialog_details.show();
                            dialog_details.getBehaviorSubject().subscribe(o -> {
                                doTcChangeStatus(position);
                                dialog_details.dismiss();
                            });
                        });
                    }
                }
            });
            recyNongchanpin.setAdapter(adapter);
            if (orderDetailsEntity.getTcData() != null) {
                adapter.setData(orderDetailsEntity.getTcData());
            }
        } else {
            recyNongchanpinLlt.setVisibility(View.GONE);
            postHouseAddrLlt.setVisibility(View.GONE);
        }

        if (orderDetailsEntity.getIs_service().equals("1")) {
            valueAddedServices.setText("已购");
        } else {
            valueAddedServices.setText("未购");
        }

        if (orderDetailsEntity.getOrderStatuText().equals("继续付款")) {

            orderDetailsWuliuXinxi.setVisibility(View.GONE);
            orderDetailsTypeEdit.setVisibility(View.VISIBLE);
            editOrderDetailsOne.setText("继续付款");
            editOrderDetailsTwo.setVisibility(View.GONE);

            orderDetailsOrderDownTime.setVisibility(View.VISIBLE);
            orderDetailsOrderCreateTime.setVisibility(View.GONE);
            orderDetailsOrderDownTime.setText("创建时间：" + orderDetailsEntity.getCreate_time());

            RxViewHelper.getInstance().clicks(editOrderDetailsOne, aVoid -> {
                Intent intent = new Intent(OrderDetailsActivity.this, FarmingPayActivity.class);
                intent.putExtra("myOrderEntity", myOrderEntity);
                startActivity(intent);
            });


        } else if (orderDetailsEntity.getOrderStatuText().equals("待付款")) {
            orderDetailsWuliuXinxi.setVisibility(View.GONE);
            orderDetailsTypeEdit.setVisibility(View.VISIBLE);
            editOrderDetailsOne.setText("付款");
            editOrderDetailsTwo.setText("取消订单");

            orderDetailsOrderDownTime.setVisibility(View.VISIBLE);
            orderDetailsOrderCreateTime.setVisibility(View.GONE);
            orderDetailsOrderDownTime.setText("创建时间：" + orderDetailsEntity.getCreate_time());

            RxViewHelper.getInstance().clicks(editOrderDetailsOne, aVoid -> {
                Intent intent = new Intent(OrderDetailsActivity.this, OrderPaymentActivity.class);
                intent.putExtra("myOrderEntity", myOrderEntity);
                startActivity(intent);
            });

            RxViewHelper.getInstance().clicks(editOrderDetailsTwo, aVoid -> {
                doCancelOrder();//取消订单
            });

        } else if (orderDetailsEntity.getOrderStatuText().equals("待发货")) {
            orderDetailsWuliuXinxi.setVisibility(View.GONE);
            orderDetailsTypeEdit.setVisibility(View.GONE);

            orderDetailsOrderDownTime.setVisibility(View.VISIBLE);
            orderDetailsOrderCreateTime.setVisibility(View.VISIBLE);
            orderDetailsOrderDownTime.setText("创建时间：" + orderDetailsEntity.getCreate_time());
            orderDetailsOrderCreateTime.setText("付款时间：" + orderDetailsEntity.getPay_time());

        } else if (orderDetailsEntity.getOrderStatuText().equals("待收货")) {
            orderDetailsWuliuXinxi.setVisibility(View.VISIBLE);
            orderDetailsTypeEdit.setVisibility(View.VISIBLE);
            editOrderDetailsOne.setVisibility(View.GONE);
            editOrderDetailsTwo.setText("确认收货");

            orderDetailsOrderDownTime.setVisibility(View.VISIBLE);
            orderDetailsOrderCreateTime.setVisibility(View.VISIBLE);
            orderDetailsOrderDownTime.setText("创建时间：" + orderDetailsEntity.getCreate_time());
            orderDetailsOrderCreateTime.setText("发货时间：" + orderDetailsEntity.getSend_time());

            RxViewHelper.getInstance().clicks(editOrderDetailsTwo, aVoid -> {
                doConfirmOrder();//确认收货
            });

        } else if (orderDetailsEntity.getOrderStatuText().equals("已完成")) {
            orderDetailsWuliuXinxi.setVisibility(View.VISIBLE);
            orderDetailsTypeEdit.setVisibility(View.VISIBLE);
            editOrderDetailsOne.setVisibility(View.GONE);
            editOrderDetailsTwo.setText("删除订单");

            orderDetailsOrderDownTime.setVisibility(View.VISIBLE);
            orderDetailsOrderCreateTime.setVisibility(View.VISIBLE);
            orderDetailsOrderDownTime.setText("创建时间：" + orderDetailsEntity.getCreate_time());
            orderDetailsOrderCreateTime.setText("完成时间：" + orderDetailsEntity.getCompletion_time());

            RxViewHelper.getInstance().clicks(editOrderDetailsTwo, aVoid -> {
                doDeleteOrder();//删除订单
            });

        } else if (orderDetailsEntity.getOrderStatuText().equals("已取消")) {
            orderDetailsTypeEdit.setVisibility(View.VISIBLE);
            editOrderDetailsOne.setVisibility(View.GONE);
            editOrderDetailsTwo.setText("删除订单");

            orderDetailsOrderDownTime.setVisibility(View.VISIBLE);
            orderDetailsOrderCreateTime.setVisibility(View.GONE);
            orderDetailsOrderDownTime.setText("创建时间：" + orderDetailsEntity.getCreate_time());

            RxViewHelper.getInstance().clicks(editOrderDetailsTwo, aVoid -> {
                doDeleteOrder();//删除订单
            });
        } else if (orderDetailsEntity.getOrderStatuText().equals("已退款")) {
            orderDetailsWuliuXinxi.setVisibility(View.GONE);
            orderDetailsTypeEdit.setVisibility(View.GONE);

            orderDetailsOrderDownTime.setVisibility(View.VISIBLE);
            orderDetailsOrderCreateTime.setVisibility(View.VISIBLE);
            orderDetailsOrderDownTime.setText("创建时间：" + orderDetailsEntity.getCreate_time());
            orderDetailsOrderCreateTime.setText("付款时间：" + orderDetailsEntity.getPay_time());
        }

        orderDetailsStatus.setText(orderDetailsEntity.getOrderStatuText());
        orderPersonPhone.setText(orderDetailsEntity.getMobile());
        orderPersonName.setText("收货人：" + orderDetailsEntity.getAccept_name());
        orderPersonAddress.setText("收货地址：" +
                orderDetailsEntity.getProvince_str() +
                orderDetailsEntity.getCity_str() +
                orderDetailsEntity.getArea_str() +
                orderDetailsEntity.getAddress());
        GlideUtils.setImageViewByThumb(OrderDetailsActivity.this,
                Config.URL_HOST_SHOP + orderDetailsEntity.getImg(),
                R.mipmap.ic_launcher,
                orderDetailsImage);
        orderDetailsPricePianyi.setText(orderDetailsEntity.getGoods_price());

        // niujifen
        if (orderDetailsEntity.getPayment_options() == 1) {
            payFlag.setImageResource(R.drawable.icon_token);
            payFlag1.setImageResource(R.drawable.icon_token);
            payFlag2.setImageResource(R.drawable.icon_token);
        } else {
            payFlag.setImageResource(R.drawable.icon_rmb);
            payFlag1.setImageResource(R.drawable.icon_rmb);
            payFlag2.setImageResource(R.drawable.icon_rmb);
        }
        orderDetailsPriceGui.setText(orderDetailsEntity.getReal_price());
        orderDetailsPriceGui.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        orderDetailsNumber.setText("x" + orderDetailsEntity.getGoods_nums());
        orderDetailsShopName.setText(orderDetailsEntity.getGoods_name());

        String goodsArray = orderDetailsEntity.getGoods_array();

        try {
            JSONObject jsonObject = new JSONObject(goodsArray);
            orderDetailsSerialNumber.setText(jsonObject.getString("goodsno"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        orderDetailsOrderNumber.setText("订单号：" + orderDetailsEntity.getOrder_no());
        orderDetailsUserMassage.setText("用户留言：" + orderDetailsEntity.getRemark());
        String wuliuInfo = orderDetailsEntity.getDeliveryInfo();

        try {
            JSONObject jsonObject = new JSONObject(wuliuInfo);
            orderDetailsWuliuGongsi.setText("物流公司：" + jsonObject.getString("freight_name"));
            orderDetailsKuaidiNumber.setText("快递单号：" + jsonObject.getString("delivery_code"));
            orderDetailsQueryUrl.setText("查询网址：" + jsonObject.getString("url"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        orderDetailsShopPrice.setText(orderDetailsEntity.getGoods_price());
        orderDetailsOrderYunfei.setText(orderDetailsEntity.getInvoice());
        orderDetailsOrderZongjia.setText(orderDetailsEntity.getSum_price());
    }

    //农产品确认收货
    private void doTcChangeStatus(int pos) {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .doTcChangeStatus(orderDetailsEntity.getOrder_id(),
                        orderDetailsEntity.getTcData().get(pos).getWeek())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast(response.getMsg());
                    }
                });
    }

    //获取订单详情
    private void getOrderDetail(String order_id) {

        NetClient.getInstance().getShopService(ShopInterface.class)
                .getOrderDetail(AppUtils.getSignParams(order_id), order_id)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<OrderDetailsEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<OrderDetailsEntity> response) {
                        if (response.getData() != null) {
                            orderDetailsEntity = response.getData();
                            for (int i = 1; i < orderDetailsEntity.getTcData().size(); i++) {
                                if (orderDetailsEntity.getTcData().get(i).getTc_detail_code() == 2) {
                                    boat = i;
                                }
                            }
                            initData(order_id);
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    // 上传套餐
    private void doActionAdd(int pos, String tcID, BaseViewHolder holder, String order_id) {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .doActionAdd(orderDetailsEntity.getOrder_id(),
                        orderDetailsEntity.getTcData().get(pos).getWeek(), tcID)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        if (response.getCode() == 1) {
                            ToastHelper.toast("第" +
                                    orderDetailsEntity.getTcData().get(pos).getWeek() + "选取成功");
                            holder.setText(R.id.taocan_text, "查看详情");
                            getOrderDetail(order_id);
                        } else {
                            ToastHelper.toast(response.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }


    //删除订单
    private void doDeleteOrder() {

        NetClient.getInstance().getShopService(ShopInterface.class)
                .doDeleteOrder(AppUtils.getSignParams(orderDetailsEntity.getOid(), "delete"), orderDetailsEntity.getOid(), "delete",myOrderEntity.getGoods_type())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast(response.getMsg());
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    //确认收货
    private void doConfirmOrder() {
        NetClient.getInstance().getShopService(ShopInterface.class)
                .doConfirmOrder(AppUtils.getSignParams(orderDetailsEntity.getOid(), "confirm"), orderDetailsEntity.getOid(), "confirm",myOrderEntity.getGoods_type())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast(response.getMsg());
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        LogUtil.printException(e);
                    }
                });
    }

    //取消订单
    private void doCancelOrder() {

        NetClient.getInstance().getShopService(ShopInterface.class)
                .doCancelOrder(AppUtils.getSignParams(orderDetailsEntity.getOid(), "cancel"), orderDetailsEntity.getOid(), "cancel",myOrderEntity.getGoods_type())
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        ToastHelper.toast(response.getMsg());
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }


}
